package net.tv90.auth.aop;

import jakarta.security.auth.message.AuthException;
import jakarta.validation.ConstraintViolationException;
import net.tv90.auth.exception.VerificationException;
import net.tv90.auth.utils.web.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 全局异常处理器
 *
 * @author TV90
 */
@RestControllerAdvice(basePackages = "net.tv90.auth.controller")
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleValidationExceptions(ConstraintViolationException ex) {
        // 可以尝试获取更详细的错误信息并构建自定义错误消息
        String errorMessage = ex.getConstraintViolations().iterator().next().getMessage();
        // 抛出自定义异常
        return Result.failed(errorMessage);
    }

    @ExceptionHandler(VerificationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handleVerificationExceptions(VerificationException e) {
        return Result.failed(e.getMessage());
    }

    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handleAuthException(AuthException e){
        return Result.failed(e.getMessage());
    }

}
